package utils
import (
	"fmt"
	"net"
	"go_code/projectExec2/common/message"
	"encoding/json"
	"encoding/binary"
	"errors"
)
//将这里这些方法关联到结构体中
type Transfer struct{
	//分析该有哪些字段
	Conn net.Conn
	Buf [8096]byte //传输时使用的缓冲
}


//封装函数，用于读传来的数据
func (this *Transfer)ReadPkg() (mes message.Message,err error){

	fmt.Println("读取客户端发送数据中...")
	_,err = this.Conn.Read(this.Buf[:4])
	if err != nil{
		//err = errors.new("read pkg header error")
		return
	}
	//将buf[:4]转成一个uint32类型的数据 传的包的长度
	var pkgLen uint32
	pkgLen = binary.BigEndian.Uint32(this.Buf[:4])

	//根据 pkgLen 读取消息内容
	n,err := this.Conn.Read(this.Buf[:pkgLen])
	if n != int(pkgLen) || err != nil{
		fmt.Println("this.Conn.Read fail err:",err)
	}

	//把pkgLen长度的data反序列化成 mes
	err = json.Unmarshal(this.Buf[:pkgLen],&mes)
	if err != nil{
		err = errors.New("read pkg body error")
		return
	}
	return 
}

//封装函数，用于发送数据
func (this *Transfer)WritePkg(data []byte) (err error){
	//先发送一个长度给对方
	var pkgLen uint32 = uint32(len(data))
	binary.BigEndian.PutUint32(this.Buf[:4],pkgLen)
	//发送长度
	_,err = this.Conn.Write(this.Buf[:4])
	if err != nil{
		fmt.Println("this.Conn.Write fail, err:",err)
		return
	}
	//发送data本身
	n,err := this.Conn.Write(data)
	if n != int(pkgLen) || err != nil{
		fmt.Println("this.Conn.Write(data) fail err:",err)
		return
	}
	return
}